package com.qcb.expresswrapping.security;

import com.qcb.expresswrapping.entity.SysVo.SysUser;
import com.qcb.expresswrapping.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2021-12-31-22:02
 * To change this template use File | Settings | File and Code Templates.
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(),
                getUserAuthority(sysUser.getId()));
    }

    /*
     * @Description: 获取用户权限信息
     * @Param: [userId]
     * @return: java.util.List<org.springframework.security.core.GrantedAuthority>
    */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        // 角色(ROLE_admin)，菜单操作权限(sys:user:list)
        String authority = sysUserService.getUserAuthority(userId);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
